package rad.framework.seam.ext;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.Install;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.core.ResourceLoader;

@Scope(ScopeType.APPLICATION)
@BypassInterceptors
@Startup
public class BundleNames {

	private String[] bundleNames; // front/back ?

	@Create
	public void onCreate() {
		List<String> bundles = Names.instance().getBundleNames();
		for (int i = bundleNames.length; i > 0; i--) {
			String name = bundleNames[i - 1];
			if (!bundles.contains(name)) {
				bundles.add(0, name);
			}
		}
	}

	public String[] getBundleNames() {
		return bundleNames;
	}

	public void setBundleNames(String[] bundleNames) {
		this.bundleNames = bundleNames;
	}

	@Scope(ScopeType.APPLICATION)
	@BypassInterceptors
	@Name("rad.framework.seam.bundlenames.names")
	@Startup
	public static class Names {

		private List<String> bundleNames = new ArrayList<String>();

		@Create
		public void onCreate() {
			bundleNames.add("messages");
		}

		public List<String> getBundleNames() {
			return bundleNames;
		}

		public static Names instance() {
			return (Names) Component.getInstance(Names.class);
		}
	}

	@Scope(ScopeType.STATELESS)
	@BypassInterceptors
	@Install(precedence = Install.APPLICATION)
	@Name("org.jboss.seam.core.resourceLoader")
	public static class ResourceLoaderExt extends ResourceLoader {
		@Override
		public String[] getBundleNames() {
			Collection<String> names = Names.instance().getBundleNames();
			// Extensions.print("BundleNames after", names);
			return names.toArray(new String[names.size()]);
		}
	}

	// static void print(String prefix, Collection<String> values) {
	// System.out.println(prefix + ": " + values);
	// }
}
